import pandas as pd
import numpy as np
import time
from datetime import datetime, timedelta
import os
# load data

# params and returns

def cal_performance(data):

    init_eq = data.equity[0]
    inst_unit_value =pd.DataFrame(data.equity / init_eq)
    inst_unit_value["pre_max"] = inst_unit_value.cummax()
    inst_unit_value["drawdown"] = inst_unit_value["equity"] - inst_unit_value["pre_max"]
    max_drawdown = min(inst_unit_value["drawdown"])

    ret_series = (data.equity.diff(1)/data.equity).iloc[1:]
    annual_ret = ret_series.mean() * 365

    sharpe = ret_series.mean()/ret_series.std() * np.sqrt(365)
    calmar = max_drawdown/annual_ret * -1
    ret = ret_series.sum()

    down_rets = ret_series
    down_rets[down_rets > 0] = 0
    down_vol = down_rets.std()* np.sqrt(365)
    Sortino = ret_series.mean() * 365/down_vol

    perform = {"sharpe":sharpe,
               "dd":max_drawdown,
               "calmar":calmar,
               "ret":ret,
               "down_vol":down_vol,
               "Sortino":Sortino
               }
    return perform




if __name__ == '__main__':

    t1 = time.time()
    name = "CTA"
    symbol_name = "btc"
    begin = datetime(2021,1, 1)
    end = datetime(2021, 12, 30)
    n = np.arange(20, 400 + 1, 4)

    training_days = 90
    validating_days = 15
    step_days = validating_days
    model_attr = "ret"

    sample_data = pd.DataFrame()

    data_set = {}
    for i in n:
        file_path = os.path.abspath('..\\output\\') + f"\\{name}{symbol_name}{i}_{symbol_name}_daily_eq.csv"
        raw_data = pd.read_csv(file_path)
        raw_data.index = pd.to_datetime(raw_data.endtime, format='%Y-%m-%d %H:%M:%S')
        raw_data = raw_data[begin:end]
        data_set[i] = raw_data
        if len(sample_data) ==0:
            sample_data = raw_data

    # main loop
    training_period = None
    verifying_period = None

    start_index = 0
    dates = sample_data.index
    start_date = dates[start_index]
    training_start_index = start_index - step_days

    training_output = pd.DataFrame()
    validating_output = pd.DataFrame()
    cor_array = []
    # loop
    while training_start_index + step_days + training_days + validating_days + 2 < len(dates):
        training_start_index = training_start_index + step_days
        training_start_date = dates[training_start_index]

        training_end_index = training_start_index + training_days
        training_end_date = dates[training_end_index]

        validating_start_index = training_end_index + 1
        validating_start_date = dates[validating_start_index]
        validating_end_index = validating_start_index + validating_days
        validating_end_date = dates[validating_end_index]

        training_output_temp = {}
        validating_output_temp = {}

        for i in n:
            data = data_set[i]
            training_data = data[training_start_date:training_end_date]
            traing_performance = cal_performance(training_data)
            training_output_temp[i] = traing_performance[model_attr]

            validating_data = data[validating_start_date:validating_end_date]
            validating_performance = cal_performance(validating_data)
            validating_output_temp[i] = validating_performance[model_attr]


        # 归一
        training_output_temp = pd.Series(training_output_temp)
        validating_output_temp = pd.Series(validating_output_temp)

        training_output_temp = (training_output_temp- np.mean(training_output_temp))/np.std(training_output_temp)
        validating_output_temp =  (validating_output_temp- np.mean(validating_output_temp))/np.std(validating_output_temp)

        correlation = training_output_temp.corr( validating_output_temp)
        cor_array.append(correlation)
        print(correlation)

        training_output[training_end_date] = pd.Series(training_output_temp)
        validating_output[training_end_date] = pd.Series(validating_output_temp)

    # print(cor_array)


    cor_array = np.nan_to_num(cor_array)
    msg = f"mean correaltion is {np.mean(cor_array)}"
    print(msg)

    msg = f"std correaltion is {np.std(cor_array)}"

    print(msg)
    import matplotlib.pyplot as plt

    ax1 = plt.subplot(111)
    ax1.set_title("cor_array")
    ax1.plot(cor_array)

    plt.show()








